package day01;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.util.Collector;


public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                    .fromElements("hello word","hello wangbadan")
                    .flatMap(new FlatMapFunction<String, Tuple2<String,Integer>>() {

                        public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                            String[] arr = value.split(" ");
                            for (String world : arr){
                                out.collect(Tuple2.of(world , 1));
                            }
                        }
                    })
                    .keyBy(r -> r.f0)
                    .reduce(new ReduceFunction<Tuple2<String, Integer>>() {
                        public Tuple2<String, Integer> reduce(Tuple2<String, Integer> value1, Tuple2<String, Integer> value2) throws Exception {
                            return Tuple2.of(value1.f0,value1.f1 + value2.f1);
                        }
                    })
                    .print();

        env.execute();
    }
}
